<?php

namespace Common\Model;

use Common\Model\AiModel;


class UserModel extends AiModel
{

   //验证此手机号码是否已经被注册
  function VerPhoneRegister($phone){
    $where['phone']=$phone;
    $info=$this->where($where)->find();
      if($info){//如果发现此手机号码
        return 1;
      }else{ //如果没有发现此手机号
       return 0;
     }
   }

    //添加新用户
   function addUser($phone,$password){
     $whereAdd['phone']   =$phone;
     $whereAdd['ctime']   =time();
     $whereAdd['password']=$password;
     $whereAdd['name']    =defaultName();
     $whereAdd['head']    =defaultHead();
     $whereAdd['sex']     ='n';
     $whereAdd['token']   =creatToken();
     $info=$this->add($whereAdd);
     if($info){
       return $info;
     }else{
       return 0;
     }
   }

    //手机号码 密码验证 查找用户
   function findone($phone,$password){
    $where['password']=$password;
    $where['phone']   =$phone;
    $info=$this->where($where)->field('id')->find();
    if($info){
     $data=$this->toIdGetUserInfo($info['id'],$field='id,head,name,phone,sex,token,birthday,pro,city,area','login');
     return $data;
   }else{
     EchoData('',0,101,'账号或者密码错误',0);
  }
}
 
 function toIdGetUserInfo($id,$field='id,head,name,phone,sex,token,birthday,pro,city,area',$type){
    $this->upToken($id);
    $where['id']=$id;
    $field=$field?$field:'*';
    $info= $this->where($where)->field($field)->find();
    $info['head']         =C('HOST_URL').$info['head'];
    $areastring=$this->toUidGetAreaId($id);
    $info['address']=D('Area')->toUidGetAddressFont($areastring);
    //只有是登录的时候才给创建sig
    if($type=='login'){
         $info['sig']=A('Im')->toUidCreatSig($id);
    }
    return em_set($info);
 }
 //通过用户id 获取 area id string
 function toUidGetAreaId($uid){
    $where['id']=$uid;
    $uInfo=$this->where($where)->find();
    return $uInfo['pro'].'-'.$uInfo['city'].'-'.$uInfo['area'];
 } 

    //通过小程序openid获取用户
   function toOpenidGetUserInfo($openid){
      $where['xiao_openid']=$openid;
      $info=$this->where($where)->field('id')->find();
      $data=$this->toIdGetUserInfo($info['id']);
      return $data;
   }

   //修改token
   function upToken($id){
     $where['id']=$id;
     $token=creatToken();
     $save['token']=$token;
     $saveinfo=$this->where($where)->save($save);
     if($saveinfo){
       return $token;
     }else{
       return 0;
     }

   } 
  //通过手机号码更新数据
   function UpToPhone($phone,$save){
       $where['phone']=$phone;
       $info=$this->where($where)->save($save);
       if($info!==false){
         return 1;
       }else{
         return 0;
       }
   }
   //通过ID更新数据
    function UpToId($id,$save){
       $where['id']=$id;
       $info=$this->where($where)->save($save);
       if($info!==false){
         return 1;
       }else{
         return 0;
       }
   }

 
}
